#include "PackageFactory.h"

#include "DevDataMgr.h"
#include "sampleSys_def.h"
#include "DataSaver.h"

DevDataMgr* DevDataMgr::m_head = NULL;

DevDataMgr::DevDataMgr() {
	memset(m_devId, 0, sizeof(m_devId));
	m_package = NULL;
	s = new(DataSaver);
	registerListener(s);
}

DevDataMgr::~DevDataMgr() {
	delete(m_head);
	delete(s);
}

DevDataMgr* DevDataMgr::getIt() {
	if (m_head == NULL) {
		m_head = new(DevDataMgr);
	}

	return m_head;
}

bool DevDataMgr::init(char* buffer, unsigned char &packageType) {
	m_package = PackeFactory::getIt()->getPackeTyp(buffer, packageType);
	if (m_package == NULL) {
		return false;
	}
	m_package->init(buffer);
	if (packageType == PACKAGE_AUTHREQ) {
		m_package->inbody(buffer + 24);
	}
	if (packageType == PACKAGE_DATAREQ) {
		m_package->inbody(buffer + 24);
	}
	
	return true;
}

Package* DevDataMgr::getPackage() {
	return m_package;
}

void DevDataMgr::registerListener(DataLister* s) {
	listenList.push_back(s);
}

void DevDataMgr::removeListener(DataLister* s) {
	std::vector<DataLister*>::iterator it;
	for (it = listenList.begin(); it != listenList.end(); it++) {
		if (*it == s) {
			listenList.erase(it);
			break;
		}
	}
}

void DevDataMgr::notify() {
	std::vector<DataLister*>::iterator it;
	for (it = listenList.begin(); it != listenList.end(); it++) {
		(*it)->init((dataPackage*)m_package, m_devId);
		printf_s("\n\nlistenList.begin()\n\n");
	}
}

void DevDataMgr::setValue(Package* package, unsigned char* devId) {
	memset(m_devId, 0, sizeof(m_devId));
	
	m_package = package;
	strcpy_s((char*)m_devId, sizeof(m_devId), (char*)devId);

	notify();
}